from turtle import Screen
from paddle import Paddle
from ball import Ball
from screenScore import ScoreScreen
from screenTable import ScreenTable
from config import SCREEN_WIDTH, SCREEN_HEIGHT, PADDLE_LENGTH, MAX_PLAYER_SCORE

screen = Screen()
screen.bgcolor("black")
screen.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
screen.title("Pong")
screen.tracer(0)

r_paddle = Paddle(SCREEN_WIDTH / 2 - 30)
l_paddle = Paddle(30 - SCREEN_WIDTH / 2)
ball = Ball()
score_screen = ScoreScreen()
screen_table = ScreenTable()

game_is_on = True

def q():
    global game_is_on
    print('quit')
    screen_table.quit()
    game_is_on = False

screen.listen()
screen.onkey(r_paddle.up, "Up")
screen.onkey(r_paddle.down, "Down")
screen.onkey(l_paddle.up, "w")
screen.onkey(l_paddle.down, "s")
screen.onkey(q, "q")


def restart_game():
    screen_table.reset()
    score_screen.reset()


while game_is_on:
    screen.update()

    if screen_table.r_score > MAX_PLAYER_SCORE or screen_table.l_score > MAX_PLAYER_SCORE:
        restart_game()

    if ball.is_paddle_hit(l_paddle, r_paddle):
        score_screen.increase(ball)
        ball.hit('hor')
    
    ball.move()

    if ball.xcor() > SCREEN_WIDTH / 2 or ball.xcor() < -SCREEN_WIDTH / 2:
        if (ball.xcor() > 0):
            screen_table.increase('l')
        else:
            screen_table.increase('r')
        ball.reset()
        score_screen.reset()

screen.exitonclick()